package com.zhsj.OkeHomeConsumption.ui.fragment.scancode;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyLazyFragment;
import com.zhsj.OkeHomeConsumption.ui.activity.HomeActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.LoginActivity;
import com.zhsj.OkeHomeConsumption.ui.fragment.scancode.mvp.ScanCodeUIInterFace;
import com.zhsj.OkeHomeConsumption.ui.fragment.scancode.mvp.SconCodePresenter;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;

import static android.content.Context.VIBRATOR_SERVICE;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 扫一扫付款
 */
public final class ScanCodeFragment extends MyLazyFragment<HomeActivity> implements QRCodeView.Delegate , ScanCodeUIInterFace {

    private static final String TAG = "ScanCode";
    private static final int REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY = 666;
    private SharedPreferanceUtils mSharePreferanceUtils = null;
    private ZBarView mZBarView;

    Unbinder unbinder;

    private SconCodePresenter mPresenter;

    private String qrcode = null;

    public static ScanCodeFragment newInstance() {
        return new ScanCodeFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_test_c;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_test_c_title;
    }


    @Override
    protected void initView() {
        mSharePreferanceUtils = new SharedPreferanceUtils(getActivity());
        mPresenter = new SconCodePresenter(getActivity(),this);
        mZBarView = findViewById(R.id.zbarview);
        mZBarView.setDelegate(this);
        //动态权限申请

        if (XXPermissions.isHasPermission(getActivity(), Permission.CAMERA)) {
            mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//                       mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别

            mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
        }else{
            XXPermissions.with(getActivity())
                    .permission(Permission.CAMERA) //不指定权限则自动获取清单中的危险权限
                    .request(new OnPermission() {

                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//                       mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别

                            mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                        }
                    });
        }


    }

    @Override
    protected void initData() {
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    @Override
    public void onStart() {
        super.onStart();
        if(mZBarView!=null){
            mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//        mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
            mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
            mZBarView.startSpot(); // 开始识别
        }



    }

    @Override
    public void onStop() {
        mZBarView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mZBarView.onDestroy(); // 销毁二维码扫描控件
        unbinder.unbind();
    }
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }
    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.i(TAG, "result:" + result);
        if (mSharePreferanceUtils.getToken().equals("")) {
            startActivity(LoginActivity.class);
        } else {
            qrcode = result;
            mPresenter.findByQrCode(result);
        }


    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        String tipText = mZBarView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                mZBarView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                mZBarView.getScanBoxView().setTipText(tipText);
            }
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.e(TAG, "打开相机出错");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mZBarView.showScanRect();

    }
    /*
    *二维码检索商家
    **
     */

    @Override
    public void findByQrCode(String context) {

        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                int status = jsonobj.optInt("status");
                if(status ==0){
                    toast("该商户已下架，无法支付");
                    return;
                }
                int id = jsonobj.optInt("id");
                String shopLogo = jsonobj.optString("shopLogo");
                String shopName = jsonobj.optString("shopName");
                // 数据对接正常
                //生成二维码
                Bundle bundle = new Bundle();
                bundle.putInt("id", id);
                bundle.putString("shopLogo", shopLogo);
                bundle.putString("shopName", shopName);
                bundle.putString("code", qrcode);
                startActivity(new Intent(getActivity(),InputPriceActivity.class).putExtras(bundle));

            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("findByQrCode", "二维码检索商家");
        }

    }
}